package com.lhn.netty.netty_demo.protocoltcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author lhn
 * @date 2025/06/11 19:44
 * @since 1.0.0
 **/
public class MyClientHandler extends SimpleChannelInboundHandler <MessageProtocol> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("MyClientHandler 发送数据");
        for (int i = 0; i < 10; i++) {
            String s = "今天天气冷吃火锅";
            byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
            MessageProtocol messageProtocol = new MessageProtocol();
            messageProtocol.setLength(bytes.length);
            messageProtocol.setContent(bytes);
            ctx.writeAndFlush(messageProtocol);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocol messageProtocol) throws Exception {
        byte[] bytes = new byte[messageProtocol.getLength()];
        messageProtocol.getContent();
        String string = new String(bytes, StandardCharsets.UTF_8);
        System.out.println("客户端接收到消息 :   " + string);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}